import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { $getSelection, $isRangeSelection, $createTextNode, $setSelection, RangeSelection } from 'lexical';
import { useCallback, useEffect, useState, useRef } from 'react';
import { createPortal } from 'react-dom';

interface AIOptimizeDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onOptimize: (description: string) => void;
  isLoading: boolean;
  hasSelectedText: boolean; // 新增：标识是否有选中文本
}

function AIOptimizeDialog({ isOpen, onClose, onOptimize, isLoading, hasSelectedText }: AIOptimizeDialogProps) {
  const [description, setDescription] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (description.trim()) {
      onOptimize(description);
      setDescription('');
    }
  };

  if (!isOpen) return null;

  // 根据是否有选中文本显示不同的界面文本
  const dialogTitle = hasSelectedText ? 'AI内容润色' : 'AI内容生成';
  const placeholderText = hasSelectedText
    ? '例如：让这段文字更简洁明了...'
    : '例如：写一段关于人工智能的介绍...';
  const buttonText = hasSelectedText ? '润色' : '生成';
  const loadingText = hasSelectedText ? '优化中...' : '生成中...';

  return createPortal(
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(0, 0, 0, 0.5)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      zIndex: 1000,
    }}>
      <div style={{
        background: 'white',
        padding: '20px',
        borderRadius: '8px',
        minWidth: '400px',
        boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
      }}>
        <h3>{dialogTitle}</h3>
        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: '14px' }}>
            <textarea
              id="description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder={placeholderText}
              style={{
                width: '400px',
                minHeight: '100px',
                padding: '8px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                resize: 'vertical',
              }}
              disabled={isLoading}
            />
          </div>
          <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
            <button
              type="button"
              onClick={onClose}
              disabled={isLoading}
              style={{
                padding: '8px 16px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                background: 'white',
                cursor: isLoading ? 'not-allowed' : 'pointer',
              }}
            >
              取消
            </button>
            <button
              type="submit"
              disabled={isLoading || !description.trim()}
              style={{
                padding: '8px 16px',
                border: 'none',
                borderRadius: '4px',
                background: isLoading ? '#ccc' : '#007bff',
                color: 'white',
                cursor: isLoading || !description.trim() ? 'not-allowed' : 'pointer',
              }}
            >
              {isLoading ? loadingText : buttonText}
            </button>
          </div>
        </form>
      </div>
    </div>,
    document.body
  );
}

export default function AIOptimizePlugin() {
  const [editor] = useLexicalComposerContext();
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedText, setSelectedText] = useState('');
  const [selectionRange, setSelectionRange] = useState<RangeSelection | null>(null);

  // 方案3: 使用 ref 保存选区信息，避免状态更新导致的延迟
  const savedSelectionRef = useRef<{
    text: string;
    range: RangeSelection;
  } | null>(null);

  const handleOptimize = useCallback(async (description: string) => {
    const savedSelection = savedSelectionRef.current;
    const hasSelectedText = savedSelection !== null;

    setIsLoading(true);
    try {
      await Promise.resolve();

      // 根据是否有选中文本构造不同的请求内容
      const requestContent = hasSelectedText
        ? `<content>${savedSelection.text}</content>  content标签是选中的内容 ${description}`
        : description; // 没有选中内容时，直接使用用户的描述

      const response = await fetch('/api/calling_agent', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          token: "NjIzNzUyNzg5MDg0MzQxMQ==:t9zmgBQwmAEQqXRnu4kxEw==",
          content: requestContent,
        }),
      });

      if (!response.ok) {
        throw new Error('API调用失败');
      }

      const result = await response.json();
      const generatedText = result.data;

      // 根据是否有选中文本执行不同的操作
      editor.update(() => {
        try {
          if (hasSelectedText) {
            // 有选中文本：替换选中内容
            $setSelection(savedSelection.range.clone());
            const selection = $getSelection();
            if ($isRangeSelection(selection)) {
              selection.removeText();
              const textNode = $createTextNode(generatedText);
              selection.insertNodes([textNode]);
            }
          } else {
            // 无选中文本：在当前光标位置插入生成的内容
            const selection = $getSelection();
            if ($isRangeSelection(selection)) {
              const textNode = $createTextNode(generatedText);
              selection.insertNodes([textNode]);
            }
          }
        } catch (error) {
          console.warn('内容插入失败:', error);
          // 备用方案：直接在当前选区插入内容
          const selection = $getSelection();
          if ($isRangeSelection(selection)) {
            const textNode = $createTextNode(generatedText);
            selection.insertNodes([textNode]);
          }
        }
      });

      setIsDialogOpen(false);
    } catch (error) {
      console.error('操作失败:', error);
      alert('操作失败，请重试');
    } finally {
      setIsLoading(false);
    }
  }, [editor]);

  useEffect(() => {
    const unregister = editor.registerUpdateListener(({ editorState }: { editorState: any }) => {
      editorState.read(() => {
        const selection = $getSelection();
        if ($isRangeSelection(selection) && !selection.isCollapsed()) {
          const text = selection.getTextContent();
          if (text.trim()) {
            setSelectedText(text);
            const clonedSelection = selection.clone();
            setSelectionRange(clonedSelection);
            // 同时保存到 ref 中，确保异步操作时可用
            savedSelectionRef.current = {
              text,
              range: clonedSelection
            };
          } else {
            setSelectedText('');
            setSelectionRange(null);
            savedSelectionRef.current = null;
          }
        } else {
          setSelectedText('');
          setSelectionRange(null);
          savedSelectionRef.current = null;
        }
      });
    });

    // 监听全局事件，允许其他组件触发弹窗
    const handleOpenDialog = () => {
      setIsDialogOpen(true);
    };

    window.addEventListener('openAIOptimizeDialog', handleOpenDialog);

    return () => {
      unregister();
      window.removeEventListener('openAIOptimizeDialog', handleOpenDialog);
    };
  }, [editor]);

  return (
    <AIOptimizeDialog
      isOpen={isDialogOpen}
      onClose={() => setIsDialogOpen(false)}
      onOptimize={handleOptimize}
      isLoading={isLoading}
      hasSelectedText={!!selectedText}
    />
  );
}